package leetcode.L500;

import leetcode.utils.ListNode;

/**
 * @Description
 * @Author yangshunjie
 * @Date 2021/10/20
 * 考虑多种情况
 */
public class EX2 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null){
            return l2;
        }
        ListNode res = l1;
        int p = 0;
        ListNode pre = new ListNode();
        pre.next = l1;
        while(l1!=null&&l2!=null){
            l1.val += l2.val+p;
            if(l1.val>9){
                l1.val = l1.val%10;
                p = 1;
            }else{
                p = 0;
            }
            l1 = l1.next;
            l2 = l2.next;
            pre = pre.next;
        }
        if(l1==null&&l2!=null){
            pre.next = l2;
        }else if(l1==null&&l2==null&&p==1){
            pre.next = new ListNode(1);
            return res;
        }
        ListNode now = pre.next;
        while(now!=null&&p==1){
            now.val +=p;
            if(now.val>9){
                now.val = now.val%10;
                p = 1;
            }else{
                p = 0;
            }
            now = now.next;
            pre = pre.next;
        }
        if(p==1&&now==null){
            pre.next = new ListNode(1);
        }
        return res;
    }
}
